import { CJLogUtil } from 'cjcommon/src/main/ets/common/CJLogUtil';
import 'reflect-metadata';
import { ColumnType } from '../db/ColumnType';
import { TableStruct, TableStructCache } from '../db/TableStructCache';
import { AnnotationEnum } from './AnnotationEnum';

const TAG = "CJDBUtil"

export const Id = (v?: {
  columnName?: string,
  types?: ColumnType,
  autoincrement?: boolean
}): PropertyDecorator => (target, primaryKey:string) => {
  let autoincrement = true
  let columnName = primaryKey
  let types = ColumnType.INTEGER
  if (v && v.columnName) {
    columnName = v.columnName
  }
  if (v && v.autoincrement) {
    autoincrement = v.autoincrement
  }
  if (v && v.types) {
    types = v.types
  }

  Reflect.defineMetadata(AnnotationEnum.IS_ID, true, target, primaryKey);
  Reflect.defineMetadata(AnnotationEnum.COLUMN, columnName, target, primaryKey);
  Reflect.defineMetadata(AnnotationEnum.TYPE, types, target, primaryKey);
  Reflect.defineMetadata(AnnotationEnum.AUTOINCREMENT, autoincrement, target, primaryKey);

  // ====================

  // CJLogUtil.info(TAG, "table cache has：" + TableStructCache.maps.has(target.constructor.name))
  if (!TableStructCache.structMaps.has(target.constructor.name)) {
    TableStructCache.structMaps.set(target.constructor.name, [])
  }
  let caches: Array<TableStruct> = TableStructCache.structMaps.get(target.constructor.name)
  caches.push({
    name: primaryKey,
    columnName: columnName,
    type: types,
    isId: true
  })
  // CJLogUtil.info(TAG, "TableStructCache：" + JSON.stringify(caches))

}